admin管理员组文章数量:1355694
I have a following class:
template<typename Population, typename... Operators> class GA
{
public:
template<typename Evaluator,
typename std::enable_if_t<
std::is_same_v<Evaluator, Evaluator<Operators...>>>>
void EvaluatePopulation(Evaluator& evaluator)
{
evaluator.Evaluate();
}
};
This doesn't compile, because of incorrect EvaluatePopulation
declaration.
How do I specify that EvaluatePopulation
method can be called only with Evaluator
class that was initialized with the same Operators...
as the GA
class?
I have a following class:
template<typename Population, typename... Operators> class GA
{
public:
template<typename Evaluator,
typename std::enable_if_t<
std::is_same_v<Evaluator, Evaluator<Operators...>>>>
void EvaluatePopulation(Evaluator& evaluator)
{
evaluator.Evaluate();
}
};
This doesn't compile, because of incorrect EvaluatePopulation
declaration.
How do I specify that EvaluatePopulation
method can be called only with Evaluator
class that was initialized with the same Operators...
as the GA
class?
1 Answer
Reset to default 9How do I specify that
EvaluatePopulation
method can be called only withEvaluator
class that was initialised with the sameOperators...
as theGA
class?
The trick is to use a template template parameter so that you “unpack” the evaluator’s template arguments to match the GA’s pack. For example, you can write:
template<typename Population, typename... Operators>
class GA
{
public:
template<template<typename...> class EvaluatorT>
void EvaluatePopulation(EvaluatorT<Operators...>& evaluator)
{
evaluator.Evaluate();
}
};
((See live demo))
Alternatively, using c++20's concepts, which gives clearer error messages:
// Ensures Evaluator is instantiated with exactly Operators...
template<typename T, typename... Args>
constexpr bool is_evaluator_for_v = false;
template<template<typename...> class EvaluatorT, typename... Ops>
constexpr bool is_evaluator_for_v<EvaluatorT<Ops...>, Ops...> = true;
template<typename Evaluator, typename... Operators>
concept EvaluatorFor = is_evaluator_for_v<Evaluator, Operators...>;
template<typename Population, typename... Operators> class GA
{
public:
template<typename Evaluator> requires EvaluatorFor<Evaluator, Operators...>
void EvaluatePopulation(Evaluator& evaluator)
{
evaluator.Evaluate();
}
};
((See live demo))
本文标签: cHow to constrain template methods to match class template parametersStack Overflow
版权声明:本文标题:c++ - How to constrain template methods to match class template parameters? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743980515a2571060.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
template<template<typename...> Evaluator> void EvaluatePopulation(Evaluator<Operators...>& evaluator)
– NathanOliver Commented Mar 30 at 17:26