在下面的代码中:
template <typename T>
struct templatedStruct
{
};
template <typename T>
void func(T arg)
{
// How to find out if T is type templatedStruct of any type, ie., templatedStruct<int> or
// templatedStruct<char> etc?
}
int main()
{
templatedStruct<int> obj;
func(obj);
}
Run Code Online (Sandbox Code Playgroud)
是从其他东西继承 templatedStruct 的唯一方法吗?
struct Base {};
template <typename T>
struct templatedStruct : Base
{
};
template <typename T>
void func(T arg)
{
std::is_base_of_v< Base, T>;
std::derived_from<T, Base>; // From C++ 20
}
Run Code Online (Sandbox Code Playgroud)
你可以为它定义一个类型特征。
template <typename T>
struct is_templatedStruct : std::false_type {};
template <typename T>
struct is_templatedStruct<templatedStruct<T>> : std::true_type {};
Run Code Online (Sandbox Code Playgroud)
然后
template <typename T>
void func(T arg)
{
// is_templatedStruct<T>::value would be true if T is an instantiation of templatedStruct
// otherwise false
}
Run Code Online (Sandbox Code Playgroud)