考虑以下:
#include <iostream>
#include <string>
/**
* Provides base functionality for any property.
*/
struct property_base
{
virtual std::string to_string() const = 0;
protected:
void notify() { std::cout << "notifying!" << std::endl; }
};
/**
* Generic property implementation template.
*/
template<typename T>
struct property_impl :
property_base
{
T data;
property_impl<T>& operator=(const T& t)
{
this->data = t;
this->notify();
return *this;
}
};
/**
* Generic property template.
*/
template<typename T>
struct property :
property_impl<T>
{
};
/**
* 'int' property specialization
*/
template<>
struct property<int> :
property_impl<int>
{
std::string to_string() const { return std::to_string(data); }
};
/**
* `std::string` property specialization
*/
template<>
struct property<std::string> :
property_impl<std::string>
{
std::string to_string() const { return data; }
};
int main()
{
property<int> x;
property<std::string> str;
x = 42;
str = "Hello World!";
return 0;
}
编译时,编译器提示找不到 operator=
的匹配项。操作数类型 property<int>
和 int
.据我了解,问题是我正在调用 property<int>::operator=(int)
这不存在。相反,我只有 property_impl<int>::operator(int)
定义。有没有一种方法可以在不需要每个
property<T>
的情况下完成这项工作?模板特化显式实现 operator=()
? operator=
的执行对于所有特化都是相同的,所以我正在寻找一种不需要显式实现 operator=
的方法为所有 future property<T>
专业。Coliru 链接到思想家:http://coliru.stacked-crooked.com/a/1db9165e4f78ffa4
最佳答案
C++ 中很少有事情是自动发生的。幸运的是,在这种情况下您不必编写很多额外的代码,只需添加一个 using
对每个子类的声明:
/**
* 'int' property specialization
*/
template<>
struct property<int> :
property_impl<int>
{
using property_impl<int>::operator=;
std::string to_string() const { return std::to_string(data); }
};
/**
* `std::string` property specialization
*/
template<>
struct property<std::string> :
property_impl<std::string>
{
using property_impl<std::string>::operator=;
std::string to_string() const { return data; }
};
您必须明确添加 using
声明到这个子类,但这仍然比复制/粘贴相同的 operator=
更好在他们每个人中。
关于c++ - 模板特化基类函数模板缺失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64912800/