[英]Template specialization base class function template missing
考慮以下:
#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;
}
編譯時,編譯器抱怨找不到操作數類型為property<int>
和int
operator=
的匹配項。 據我了解,問題是我正在調用不存在的property<int>::operator=(int)
。 相反,我只定義了property_impl<int>::operator(int)
。
有沒有辦法在不需要每個property<T>
模板特化來顯式實現operator=()
的情況下完成這項工作? operator=
的實現對於所有專業化都是相同的,所以我正在尋找一種不需要為所有未來的property<T>
專業化明確實現的operator=
的方法。
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=
更好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.