C++ 默认类型转换可以';t在SFINAE'中推导模板参数;d转换运算符
考虑下面的代码。我的意图是根据C++ 默认类型转换可以';t在SFINAE'中推导模板参数;d转换运算符,c++,templates,template-specialization,sfinae,C++,Templates,Template Specialization,Sfinae,考虑下面的代码。我的意图是根据struct B的模板类型参数使用不同的转换运算符(隐式) #include <type_traits> #include <iostream> using namespace std; // just to simplify syntax template <bool Tp_bool, typename Tp = void> using Enable_if = typename std::enable_if<Tp_bo
struct B
的模板类型参数使用不同的转换运算符(隐式)
#include <type_traits>
#include <iostream>
using namespace std;
// just to simplify syntax
template <bool Tp_bool, typename Tp = void>
using Enable_if = typename std::enable_if<Tp_bool, Tp>::type;
template<typename T>
struct B {
T m_value;
explicit B(T val = T{}) :
m_value{val}
{ }
template<typename Q = T, Enable_if<sizeof(Q) < sizeof(int), int> = 0 >
operator size_t(){
cout << "narrow T\n";
return static_cast<size_t>(m_value);
}
template<typename Q = T, Enable_if<sizeof(Q) >= sizeof(int), int> = 0 >
operator Q(){
cout << "wide T\n";
return m_value;
}
};
int main() {
B<int> b{5};
char* pc = new char[b]; // !!!compile-time error here!!!
if(b == 5) /*no-op*/; // unrem the line above to see that SFINAE works fine
return 0;
}
#包括
#包括
使用名称空间std;
//只是为了简化语法
模板
使用Enable_if=typename std::Enable_if::type;
模板
结构B{
T m_值;
显式B(T val=T{}):
m_值{val}
{ }
模板
运算符大小\u t(){
库特
算子Q(){
库特
B::运算符Q()[其中Q=Q;
typename std::enable_if=sizeof(int)),int>::type=;T=int]'
是什么原因导致了这种情况,我该如何使其工作?如果
启用\u,请显示实际代码。@某个程序员说得对,很抱歉。现在完成了。你是说运算符大小\u t
还是运算符Q
在狭义情况下?你可以使用std::如果启用\u\t
而不是你的自定义别名。与literal 5正在转换为int,因此狭义大小写(返回一个size_t)不会特别重要。在数组中,您正在转换为size_t,因此可能的候选值是运算符size_t()
和操作员大小
,操作员大小
,操作员大小
,等等。您想的最后一个是哪一个?
error: default type conversion can't deduce template argument for
'template<class Q, typename std::enable_if<(sizeof (Q) >= sizeof (int)), int>::type <anonymous> >
B<T>::operator Q() [with Q = Q;
typename std::enable_if<(sizeof (Q) >= sizeof (int)), int>::type <anonymous> = <enumerator>; T = int]'