我不清楚你到底想要什么。
如果您希望 my_method() 仅在 T 是其中包含 value_type 类型的类/结构时实现,并且您希望在使用 T 而没有 value_type 调用时出现编译错误它,我建议通过declval()和decltype()使用SFINAE。
某事
template <typename T>
auto my_method ()
-> decltype( std::declval<typename T::value_type>(), void() )
{ }
如果可以使用 C++17,而不是 decltype( std::declval<typename T::value_type>(), void() ),则可以使用 std::void_t<T::value_type>。
如果您想要一个具有更通用版本的my_method() 和一个带有value_type 的类/结构的专用版本,我建议开发一个通用my_method(),它只需调用另一个方法my_method_helper() 添加int 值
template <typename T>
void my_method ()
{ my_method_helper<T>(0); }
并将my_method_helper() 的 SFINAE 和函数重载与接收 long(所以不完全是 int)的 my_method_helper() 相结合,并且已为更通用的版本启用
template <typename T>
void my_method_helper (long)
{ }
以及恰好接收int 的版本(因此,如果可用,则优先于long 版本)但仅当T 包含value_type 时才启用。
template <typename T>
auto my_method_helper (int)
-> decltype( std::declval<typename T::value_type>(), void() )
{ }
所以当T 包含value_type 时调用my_method_helper(int),否则调用my_method_helper(long)。
以下是一个完整的编译示例(方法名已更改)
#include <utility>
#include <iostream>
struct MyClass
{
template <typename T>
auto method_1 ()
-> decltype( std::declval<typename T::value_type>(), void() )
{ std::cout << "method_1 " << std::endl; }
template <typename T>
auto method_2 (int)
-> decltype( std::declval<typename T::value_type>(), void() )
{ std::cout << "method_2 specialized" << std::endl; }
template <typename T>
void method_2 (long)
{ std::cout << "method_2 generic" << std::endl; }
template <typename T>
void method_2 ()
{ method_2<T>(0); }
};
struct foo
{ using value_type = int; };
int main()
{
MyClass mc;
mc.method_1<foo>();
// mc.method_1<int>(); // compilation error
mc.method_2<foo>(); // call specialized version
mc.method_2<int>(); // call generic version
}
部分偏离主题:我不明白“语法适用于函数”是什么意思
template<class T, class... Assertions> void my_function();
template <class list_t, class list_t::value_type>
void my_function() { }
你怎么称呼my_function()?