转换运算符模板特化
这是一个理解转换运算符、模板和模板特化的主要学术练习。以下代码中的转换运算符模板适用于 int
、float
和 double
,但与 std::string 一起使用时失败
...有点。我创建了到 std::string
的转换的专门化,它在与初始化 std::string s = a;
一起使用时有效,但在与 a 一起使用时失败强制转换 static_cast
。
#include <iostream>
#include <string>
#include <sstream>
class MyClass {
int y;
public:
MyClass(int v) : y(v) {}
template <typename T>
operator T() { return y; };
};
template<>
MyClass::operator std::string() {
std::stringstream ss;
ss << y << " bottles of beer.";
return ss.str();
}
int main () {
MyClass a(99);
int i = a;
float f = a;
double d = a;
std::string s = a;
std::cerr << static_cast<int>(a) << std::endl;
std::cerr << static_cast<float>(a) << std::endl;
std::cerr << static_cast<double>(a) << std::endl;
std::cerr << static_cast<std::string>(a) << std::endl; // Compiler error
}
上面的代码在 g++ 和 icc 中生成编译器错误,两者都抱怨没有用户定义的转换适合将 MyClass
实例转换为 std::string
上的 < code>static_cast (C 风格的强制转换行为相同)。
如果我用转换运算符的显式非模板版本替换上述代码,一切都会很高兴:
class MyClass {
int y;
public:
MyClass(int v) : y(v) {}
operator double() {return y;}
operator float() {return y;}
operator int() {return y;}
operator std::string() {
std::stringstream ss;
ss << y << " bottles of beer.";
return ss.str();
}
};
我的 std::string
模板专业化有什么问题?为什么它可以用于初始化但不能进行强制转换?
更新:
经过 @luc-danton 的一些模板魔法(我以前从未见过的元编程技巧),在启用实验性 C++0x 扩展后,我在 g++ 4.4.5 中运行了以下代码。除了这里所做的事情令人恐惧之外,需要实验性编译器选项本身就是不这样做的理由。无论如何,这希望对其他人和我一样具有教育意义:
class MyClass {
int y;
public:
MyClass(int v) : y(v) {}
operator std::string() { return "nobody"; }
template <
typename T
, typename Decayed = typename std::decay<T>::type
, typename NotUsed = typename std::enable_if<
!std::is_same<const char*, Decayed>::value &&
!std::is_same<std::allocator<char>, Decayed>::value &&
!std::is_same<std::initializer_list<char>, Decayed>::value
>::type
>
operator T() { return y; }
};
这显然迫使编译器为 std::string
选择转换 operator std::string()
,它可以克服编译器遇到的任何歧义。
Here's a largely academic exercise in understanding conversion operators, templates and template specializations. The conversion operator template in the following code works for int
, float
, and double
, but fails when used with std::string
... sort of. I've created a specialization of the conversion to std::string
, which works when used with initialization std::string s = a;
, but fails when used with a cast static_cast<std::string>(a)
.
#include <iostream>
#include <string>
#include <sstream>
class MyClass {
int y;
public:
MyClass(int v) : y(v) {}
template <typename T>
operator T() { return y; };
};
template<>
MyClass::operator std::string() {
std::stringstream ss;
ss << y << " bottles of beer.";
return ss.str();
}
int main () {
MyClass a(99);
int i = a;
float f = a;
double d = a;
std::string s = a;
std::cerr << static_cast<int>(a) << std::endl;
std::cerr << static_cast<float>(a) << std::endl;
std::cerr << static_cast<double>(a) << std::endl;
std::cerr << static_cast<std::string>(a) << std::endl; // Compiler error
}
The above code generates a compiler error in g++ and icc, both complaining that no user-defined conversion is suitable for converting a MyClass
instance to a std::string
on the static_cast
(C-style casts behave the same).
If I replace the above code with explicit, non-template versions of the conversion operator, everything is happy:
class MyClass {
int y;
public:
MyClass(int v) : y(v) {}
operator double() {return y;}
operator float() {return y;}
operator int() {return y;}
operator std::string() {
std::stringstream ss;
ss << y << " bottles of beer.";
return ss.str();
}
};
What is wrong with my template specialization for std::string
? Why does it work for initialization but not casting?
Update:
After some template wizardry by @luc-danton (meta-programming tricks I'd never seen before), I have the following code working in g++ 4.4.5 after enabling experimental C++0x extensions. Aside from the horror of what is being done here, requiring experimental compiler options is reason enough alone to not do this. Regardless, this is hopefully as educational for others as it was for me:
class MyClass {
int y;
public:
MyClass(int v) : y(v) {}
operator std::string() { return "nobody"; }
template <
typename T
, typename Decayed = typename std::decay<T>::type
, typename NotUsed = typename std::enable_if<
!std::is_same<const char*, Decayed>::value &&
!std::is_same<std::allocator<char>, Decayed>::value &&
!std::is_same<std::initializer_list<char>, Decayed>::value
>::type
>
operator T() { return y; }
};
This apparently forces the compiler to choose the conversion operator std::string()
for std::string
, which gets past whatever ambiguity the compiler was encountering.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以通过仅使用与 GCC 的实际错误结合来重现问题
(
错误:重载的'basic_string(MyClass&)'调用不明确
)我们有关于可能发生的情况的强有力线索:是复制初始化 (std::string s = a;
) 和直接初始化情况下的一种首选转换序列(std::string t(a);
和static_cast
)至少有两个序列,其中一个不能优先于另一个。查看所有带有一个参数的 std::basic_string 显式构造函数(在直接初始化期间唯一考虑的构造函数,而不是复制初始化),我们发现显式 basic_string(const Allocator& a = Allocator()); 这实际上是唯一的显式构造函数。
不幸的是,除了诊断之外,我无能为力:我想不出一个技巧来发现
operator std::allocator
是否已实例化(我尝试了 SFINAE 和operator std::allocator() = delete;
,没有成功),而且我对函数模板特化、重载解析和库要求知之甚少,无法知道 GCC 的行为是否符合或 不是。既然你说这个练习是学术性的,我就不再像往常一样谩骂你,非显式转换运算符不是一个好主意。我认为你的代码是一个足够好的例子来说明为什么:)
我让 SFINAE 工作。如果运算符声明为:
那么就不存在歧义,并且代码将编译,将选择 std::string 的特化,并且生成的程序将按预期运行。我仍然没有解释为什么复制初始化没问题。
You can reproduce the problem by just using
Combined with the actual error from GCC (
error: call of overloaded 'basic_string(MyClass&)' is ambiguous
) we have strong clues as to what may be happening: there is one preferred conversion sequence in the case of copy initialization (std::string s = a;
), and in the case of direct initialization (std::string t(a);
andstatic_cast
) there are at least two sequences where one of them can't be preferred over the other.Looking at all the
std::basic_string
explicit constructors taking one argument (the only ones that would be considered during direct initialization but not copy initialization), we findexplicit basic_string(const Allocator& a = Allocator());
which is in fact the only explicit constructor.Unfortunately I can't do much beyond that diagnostic: I can't think of a trick to discover is
operator std::allocator<char>
is instantiated or not (I tried SFINAE andoperator std::allocator<char>() = delete;
, to no success), and I know too little about function template specializations, overload resolution and library requirements to know if the behaviour of GCC is conforming or not.Since you say the exercise is academic, I will spare you the usual diatribe how non-explicit conversion operators are not a good idea. I think your code is a good enough example as to why anyway :)
I got SFINAE to work. If the operator is declared as:
Then there is no ambiguity and the code will compile, the specialization for
std::string
will be picked and the resulting program will behave as desired. I still don't have an explanation as to why copy initialization is fine.这里的
static_cast
相当于std::string(a)
。请注意,
std::string s = std::string(a);
也无法编译。我的猜测是,构造函数有很多重载,并且模板版本可以将a
转换为许多合适的类型。另一方面,对于固定的转换列表,只有其中一个与字符串构造函数接受的类型完全匹配。
要测试这一点,请添加到
const char*
的转换 - 非模板化版本应该在同一位置开始失败。(现在的问题是为什么
std::string s = a;
有效。它和std::string s = std::string(a);
之间的细微差别是只有神才知道。)static_cast
here is equivalent of doingstd::string(a)
.Note that
std::string s = std::string(a);
doesn't compile either. My guess is, there are plenty of overloads for the constructor, and the template version can converta
to many suitable types.On the other hand, with a fixed list of conversions, only one of those matches exactly a type that the string's constructor accepts.
To test this, add a conversion to
const char*
- the non-templated version should start failing at the same place.(Now the question is why
std::string s = a;
works. Subtle differences between that andstd::string s = std::string(a);
are only known to gods.)