有没有办法强制用户显式指定模板参数类型?
Is there a way to force the user to explicitly specify the template argument type?
简短版:我有一个模板函数,它是"universal",但我想强制用户明确指定参数的类型,它们作为参数传递给这个函数。
有什么想法吗?
长版:听起来是个糟糕的设计,但这是我的情况,目前我想不出更好的选择。
我正在尝试 "implement" ::setsockopt
在一个小的 socket
class 中(我不想有大量的函数,采用不同的参数和做同样的事情)。例如:
template< typename OPTION_VALUE_TYPE >
bool set_option( int level, int option_name, const OPTION_VALUE_TYPE& value )
{
return -1 != ::setsockopt( fd_, level, option_name, &value, sizeof( value ) );
}
但是,这可能会导致以下情况 - 使用 1
调用 set_option
,尝试设置 unsigned char
选项将导致失败,因为 1
是 int
。正确的用法是:
set_option< unsigned char >( level, option, 1 );
作为
set_option( level, option, 1 );
可以完美编译,但会出现严重错误。
将模板类型放在非推导上下文中,如下所示:
template <typename T> struct identity { using type = T; };
template <typename OPTION_VALUE_TYPE>
bool set_option(int level,
int option_name,
const typename identity<OPTION_VALUE_TYPE>::type& value);
是的,您只需要以一种无法从参数中推导出来的方式使用模板参数。一种常见的做法是在模板中使用 typedef class:
template <typename T>
struct identity {
typedef T type;
};
template <typename OPTION_VALUE_TYPE>
bool set_option(int level, int option_name,
typename identity<const OPTION_VALUE_TYPE&>::type value);
要使用标准库中已经存在的类型,您可以使用 enable_if
:
template <typename OPTION_VALUE_TYPE>
bool set_option(int level, int option_name,
typename std::enable_if<true, const OPTION_VALUE_TYPE&>::type value);
不允许类型参数推导的原因是因为编译器不能排除 identity
的特化:编译器不能排除你做
template <>
struct identity<U> { typedef V type; };
其中 identity<U>::type
将不再是 U
。
简短版:我有一个模板函数,它是"universal",但我想强制用户明确指定参数的类型,它们作为参数传递给这个函数。
有什么想法吗?
长版:听起来是个糟糕的设计,但这是我的情况,目前我想不出更好的选择。
我正在尝试 "implement" ::setsockopt
在一个小的 socket
class 中(我不想有大量的函数,采用不同的参数和做同样的事情)。例如:
template< typename OPTION_VALUE_TYPE >
bool set_option( int level, int option_name, const OPTION_VALUE_TYPE& value )
{
return -1 != ::setsockopt( fd_, level, option_name, &value, sizeof( value ) );
}
但是,这可能会导致以下情况 - 使用 1
调用 set_option
,尝试设置 unsigned char
选项将导致失败,因为 1
是 int
。正确的用法是:
set_option< unsigned char >( level, option, 1 );
作为
set_option( level, option, 1 );
可以完美编译,但会出现严重错误。
将模板类型放在非推导上下文中,如下所示:
template <typename T> struct identity { using type = T; };
template <typename OPTION_VALUE_TYPE>
bool set_option(int level,
int option_name,
const typename identity<OPTION_VALUE_TYPE>::type& value);
是的,您只需要以一种无法从参数中推导出来的方式使用模板参数。一种常见的做法是在模板中使用 typedef class:
template <typename T>
struct identity {
typedef T type;
};
template <typename OPTION_VALUE_TYPE>
bool set_option(int level, int option_name,
typename identity<const OPTION_VALUE_TYPE&>::type value);
要使用标准库中已经存在的类型,您可以使用 enable_if
:
template <typename OPTION_VALUE_TYPE>
bool set_option(int level, int option_name,
typename std::enable_if<true, const OPTION_VALUE_TYPE&>::type value);
不允许类型参数推导的原因是因为编译器不能排除 identity
的特化:编译器不能排除你做
template <>
struct identity<U> { typedef V type; };
其中 identity<U>::type
将不再是 U
。