重载使用SNIFAE的模板类的模板操作符

问题描述 投票:0回答:1

我有一个模板类(带有 SNIFAE 条件),我想重载模板运算符 << for it.

此代码有效,但它也允许所有操作员<< overloaded for all types T to access Foo as friends.

我怎样才能获得唯一的运营商<< of type Foo to be friend of Foo class?

我尝试了 Foo 类和运算符的前向声明,但由于使用了enable_if,可以使其工作

有人知道如何做到这一点吗?

template< typename T, enable_if_t< condition_v<T>, int> = 0 >
class Foo
{
    ...

    template< typename Ar, typename R> friend Ar& operator<<(Ar& os, const Foo<R>& foo);          
};

template< typename Ar, typename T>
inline Ar& operator<<(Ar& ar, const Foo<T>& foo)
{
   ...
   return ar;
}            
c++ templates overloading
1个回答
0
投票

解决

friend
template
问题的最简单方法是在类中定义
friend
,通常:

template< typename T, std::enable_if_t< condition_v<T>, int> = 0 >
class Foo
{
    template< typename Ar > friend Ar& operator<<(Ar& os, const Foo& foo) {
        // ...
        return os;
    }          
};

请注意,这定义了一个函数模板,其中

Foo
不是模板参数。 只有
Ar
是模板参数。 这通常是可取的,因为它简化了重载解析,可以修复一些不明确的情况,并且可以提高编译速度。

© www.soinside.com 2019 - 2024. All rights reserved.