我一直在尝试根据是否operator<<(std::ostream&, const T&)存在过载来在两个模板化函数之间进行选择.
例:
template <typename T, typename std::enable_if</* ? */, int>::type = 0>
std::string stringify(const T& t)
{
std::stringstream ss;
ss << t;
return ss.str();
}
template <typename T, typename std::enable_if</* ? */, int>::type = 0>
std::string stringify(const T& t)
{
return "No overload of operator<<";
}
struct Foo { };
int main()
{
std::cout << stringify(11) << std::endl;
std::cout << stringify(Foo{}) << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
这可能吗?如果是这样,你会如何解决这个问题?
我试图将成员函数的主体作为宏参数传递。是否可以更改下面的代码以使其正常工作?
macro_rules! iterator{
($ty:ty, $ident:ident; $($state_ident:ident: $state_ty:ty), *; $next:block) => (
struct $ident { // ^ the parameter
$($state_ident: $state_ty), *
}
impl Iterator for $ident {
type Item = $ty;
fn next(&mut self) -> Option<$ty> {
$next // <- cannot refer to 'self' parameter in this block
}
}
);
}
iterator!(i32, TestIterator; index: i32; {
let value = Some(self.index);
self.index += 1;
value
});
Run Code Online (Sandbox Code Playgroud)
编译器错误:
macro_rules! iterator{
($ty:ty, $ident:ident; $($state_ident:ident: $state_ty:ty), *; $next:block) => (
struct $ident …Run Code Online (Sandbox Code Playgroud)