Как удалить специфицированный шаблон шаблона c с ключевым словом delete в C ++ - PullRequest
1 голос
/ 09 марта 2020

Я пытаюсь понять некоторые случаи использования ключевого слова delete в C ++ 11.

Поэтому я попытался удалить специализацию шаблона класса c, удалив его конструктор в методе main.

Вот мой код:

using namespace std;

template <typename T>
class ComplexNumber
{
   T x;
   T y;    
   public:
      ComplexNumber(T a, T b) : x(a) , y(b) {}        
      void display()  {    std::cout<<x << " + i"<<y<<std::endl;   }
};

int main()
{
    ComplexNumber(char a, char b) = delete;
    ComplexNumber<int> obj1(1,2);
    ComplexNumber<double> obj2(1.0,2.0);
    ComplexNumber<char> obj3('1' , '2');
    return 0;
}

Но выполнение программы не блокируется в «ComplexNumber obj3 ('1', '2')", как ожидалось, а в строке «ComplexNumber (char a, char b) = delete».

Вот ошибки » trace:

main.cpp: In function ‘int main()’:
main.cpp:28:18: error: missing template arguments before ‘(’ token
ComplexNumber(char a, char b) = delete;
              ^
main.cpp:28:19: error: expected primary-expression before ‘char’
ComplexNumber(char a, char b) = delete;
               ^~~~
main.cpp:28:27: error: expected primary-expression before ‘char’
ComplexNumber(char a, char b) = delete;
                       ^~~~
main.cpp:28:43: error: expected primary-expression before ‘;’ token
ComplexNumber(char a, char b) = delete;

Не могли бы вы помочь понять, почему мы не можем удалить указанный c конструктор "для типа char" здесь?

Ответы [ 2 ]

0 голосов
/ 09 марта 2020

Какого эффекта вы хотите добиться?

Пользователь получает сообщение об ошибке при попытке создать экземпляр вашего класса с помощью char. Здесь я бы использовал static_assert с полезным сообщением:

template <typename T>
class ComplexNumber
{
  static_assert(!std::is_same_v<char, T>, 
                "char is not allowed because .... consider using ??? instead.");

  // ...
};

Обычно вы хотите = delete один (или более) из ваших конструкторов, когда сам конструктор является шаблоном функции:

class MyComplexNumber
{
  double _re;
  double _im;

public:
  template <typename T>
  MyComplexNumber(T re, T im) : _re(re), _im(im) { }

  MyComplexNumber(char, char) = delete;
};
0 голосов
/ 09 марта 2020

Более идиоматический c способ наложить ограничение на ваш шаблон - использовать static_assert.

#include <iostream>

using namespace std;

template <typename T>
class ComplexNumber
{
   static_assert(!std::is_same_v<T, char>);
   T x;
   T y;    
   public:
      ComplexNumber(T a, T b) : x(a) , y(b) {}
      void display()  {    std::cout<<x << " + i"<<y<<std::endl;   }
};

int main()
{
    ComplexNumber<int> obj1(1,2);
    ComplexNumber<double> obj2(1.0,2.0);
    ComplexNumber<char> obj3('1' , '2');
    return 0;
}
...