【发布时间】:2020-09-24 22:55:21
【问题描述】:
我想传递一个std::less,但将它作为模板传递给一个类,如下所示:
template<typename Comparator>
class MyClass{
static Comparator comp;//Looks like this class in not multithread-safe :p
public:
int value;
bool operator<(const MyClass& other){return comp(this->value, other.value);}
};
int main()
{
cout << boolalpha;
MyClass<std::less<int> > mc1{3};
MyClass<std::less<int> > mc2{5};
cout << (mc1 < mc2) << endl;
return 0;
}
但是在mc1 和mc2 的初始化中我得到了错误:
对 `MyClass<:less> >::comp' 的未定义引用
我怎样才能做到这一点? (没有任何改变将std::less 作为参数传递给类的策略等)?
【问题讨论】:
-
can't reproduce,您使用的是哪个编译器?您在模板实例化中使用
> >而不是>>的事实让我认为您使用的是 C++11 之前的编译器。因此,与任何其他static变量一样,您可能需要在类声明之外为comp添加存储定义,例如:std::less<int> MyClass<std::less<int> >::comp; -
@RemyLebeau
static变量仅被声明,未定义。这不应该编译。 -
@Fureeish 我知道这一点,但它 does compile 对我来说没有单独的定义
comp -
@RemyLebeau 它编译,但它doesn't link。
-
注意你可能不需要
comp:godbolt.org/z/nPdbnP
标签: c++ templates comparator