小编Kyl*_*yes的帖子

使用SFINAE根据函数的特定过载是否存在来选择函数

我一直在尝试根据是否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)

这可能吗?如果是这样,你会如何解决这个问题?

c++ c++11

14
推荐指数
1
解决办法
1608
查看次数

将成员函数体作为宏参数传递

我试图将成员函数的主体作为宏参数传递。是否可以更改下面的代码以使其正常工作?

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)

rust

7
推荐指数
1
解决办法
5186
查看次数

标签 统计

c++ ×1

c++11 ×1

rust ×1