gpt4 book ai didi

c++ - 允许/禁用模板的特定复制构造函数和赋值操作

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:12:05 28 4
gpt4 key购买 nike

我想知道是否可以使用模板实现某些功能。我想要做的是允许特定的“复制构造函数和赋值运算符”从一个模板到另一个模板并禁用其他模板。

我想我只完成了一件我想要的事情,所以我提供了下面的类(class)。对于复制构造函数或赋值运算符,我希望能够执行以下操作

  • Foo<false>Foo<false>总是好的
  • Foo<true>只允许复制或分配给 Foo<false>

我不确定这是否可能......

#include <iostream>
#include <type_traits>
using namespace std;

template<bool Owner>
class Foo
{
static constexpr bool owner_ = Owner;

public:
Foo() {std::cout << "ctor\n";}
Foo operator=(const Foo& foo) { std::cout << "assignment\n";}
Foo(const Foo& foo) { std::cout << "copy ctor \n"; }

template <bool U>
Foo( const Foo<U>& other)
{
std::cout << "copy ctor2 \n";
}

template <bool U>
Foo<false>& operator=( const Foo<U>& other)
{
std::cout << "assignment 2 \n";
return *this;
}

template < bool B_ = Owner, typename = std::enable_if_t <B_> >
void bar1() {
std:cout << "bar1 " << owner_ << "\n";
}

void bar2() {std:cout << "bar2 " << owner_ << "\n";}
};

目前我唯一成功的是operator=将为 Foo<false> 工作= Foo<true> . Foo<false>Foo<false>没问题,但这也允许所有其他转换,所以 Foo<true>Foo<true>是可能的。

最佳答案

当然可以。在 C++ 中一切皆有可能。

关于所有组合的预期行为是什么,您的问题并不是 100% 清楚,但这很容易进行微调:

#include <iostream>

// Helper class

template<bool from, bool to> class ok_to_copy_foos;

// Define all valid conversions as specializations:

template<>
class ok_to_copy_foos<false, false> {

public:
typedef bool type;
};

template<>
class ok_to_copy_foos<true, false> {

public:
typedef bool type;
};

////////////////////////////////////////////////////////////////////

template<bool Owner>
class Foo {

public:

Foo() {}

template<bool U, typename allow=typename ok_to_copy_foos<U, Owner>::type>
Foo(const Foo<U> &)
{
std::cout << "copy ctor \n";
}

template<bool U, typename allow=typename ok_to_copy_foos<U, Owner>::type>
Foo &operator=(const Foo<U> &)
{
std::cout << "assignment\n";

return *this;
}
};

void foo()
{
Foo<false> f1;
Foo<true> t1;

// These ones will compile:
Foo<false> f2(f1);
f2=f1;
f2=t1;

// These ones will not compile
//
// t1=f2;
// Foo<true> t2(f2);
}

编辑:看起来还需要添加显式复制构造函数和赋值运算符。删除默认值是不够的:

Foo(const Foo &o)
{
typename ok_to_copy_foos<Owner, Owner>::type dummy;
}

Foo &operator=(const Foo &o)
{
typename ok_to_copy_foos<Owner, Owner>::type dummy;

return *this;
}

关于c++ - 允许/禁用模板的特定复制构造函数和赋值操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39671377/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com