相关疑难解决方法(0)

如何将模板化的struct/class声明为朋友?

我想做以下事情:

template <typename T>
struct foo
{
    template <typename S>
    friend struct foo<S>;

private:
    // ...
};
Run Code Online (Sandbox Code Playgroud)

但我的编译器(VC8)扼杀了它:

error C3857: 'foo<T>': multiple template parameter lists are not allowed
Run Code Online (Sandbox Code Playgroud)

我想有所有可能的实例template struct foo朋友foo<T>所有T.

我该如何工作?

编辑:这个

template <typename T>
struct foo
{
    template <typename>
    friend struct foo;

private:
    // ...
};
Run Code Online (Sandbox Code Playgroud)

似乎编译,但它是否正确?朋友和模板的语法非常不自然.

c++ templates friend

54
推荐指数
1
解决办法
2万
查看次数

C++“强制构造函数”无法访问私有成员

我正在尝试编写一些使用“成员模板强制”模式的代码,以便创建一个可以保存指向多种类型的指针并以多态方式处理它们的容器。

我在尝试编写“强制构造函数”时遇到了问题?(我不确定你真正会怎么称呼它),但是我的代码无法编译,说明我无法访问该类的私有成员。

常规复制构造函数工作正常并且确实具有访问权限,但由于某种原因使用不同的模板类型突然导致它失去访问权限。

#include <boost/shared_ptr.hpp>

template <typename T>
class Container {
public:
    Container<T>(T* contents) : m_contents(contents) {}

    // Copy constructor
    Container<T>(const Container<T>& other) : m_contents(other.m_contents) {}

    // Coercion constructor?
    template <typename U>
    Container<T>(const Container<U>& other) : m_contents(other.m_contents) {}

    T* get_contents() {
        return m_contents;
    }

private:
    T* m_contents;
};

// Things for the container to hold
struct A {};
struct B : public A {};

int main() {
    B* object1 = new B;
    Container<B> container1(object1);

    // Works fine
    Container<B> …
Run Code Online (Sandbox Code Playgroud)

c++ templates coercion copy-constructor private-members

5
推荐指数
0
解决办法
484
查看次数