Error default argument for template parameter for class enclosing

  • Forum
  • Beginners
  • error: default argument for template par

error: default argument for template parameter for class enclosing

I am trying to implement a std::list-like doubly linked list and when defining a constructor I am coming across an error that I don’t quite understand.

The stripped down code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>

template <typename T>
class List
{
public: 
   template<typename InputIt, typename = std::_RequireInputIter<InputIt>>
   List(InputIt first, InputIt last);

};

template<typename T>
template<typename InputIt, typename = std::_RequireInputIter<InputIt>>
List<T>::List(InputIt first, InputIt last)
{
   // some code here
}


int main()
{

}

When trying to compile an error is thrown:

error: default argument for template parameter for class enclosing 'List<T>::List(InputIt, InputIt)'|

The error message is not clear for me, anyone to shine a light?
Thanks!!

Last edited on

template<typename T>
template<typename InputIt, typename = std::_RequireInputIter<InputIt>>
List<T>::List(I….

Why do you have two template things stacked on top of each other?

@highwayman

template<typename T> is for List<T>

template<typename InputI... is for List(InputIt first, InputIt last)

Ahhh wait I get it now ok cool.

Default arguments only belong in the declaration:

1
2
3
4
5
6
template<typename T>
template<typename InputIt, typename>
List<T>::List(InputIt first, InputIt last)
{
   // some code here
}

Last edited on

@mbozzi oh I see, Thanks

Is there any workaround for that?

Last edited on

Yes, if it wasn’t clear from the above, here’s a version that compiles:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>

template <typename T>
class List
{
public: 
   template<typename InputIt, typename = std::_RequireInputIter<InputIt>>
   List(InputIt first, InputIt last);

};

template<typename T>
template<typename InputIt, typename>
List<T>::List(InputIt first, InputIt last)
{
   // some code here
}

int main()
{

} 

Topic archived. No new replies allowed.

21 / 19 / 7

Регистрация: 14.03.2014

Сообщений: 249

1

04.11.2017, 00:22. Показов 1665. Ответов 36


ISO 14882:2003 14.5.4.3/2

If a member template of a class template is partially specialized, the member template partial specializations
are member templates of the enclosing class template; if the enclosing class template is instantiated
(14.7.1, 14.7.2), a declaration for every member template partial specialization is also instantiated as part of
creating the members of the class template specialization. If the primary member template is explicitly specialized
for a given (implicit) specialization of the enclosing class template, the partial specializations of the
member template are ignored for this specialization of the enclosing class template. If a partial specialization
of the member template is explicitly specialized for a given (implicit) specialization of the enclosing
class template, the primary member template and its other partial specializations are still considered for this
specialization of the enclosing class template.

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

Добавлено через 22 минуты
Или инстацирование объявления это такая фигура речи. Вроде как инстанцировали, но понарошку.

Добавлено через 2 часа 27 минут
И почему

Expressions of the following forms are never type-dependent (because the type of the expression cannot be
dependent):
literal
postfix-expression . pseudo-destructor-name
postfix-expression -> pseudo-destructor-name
sizeof unary-expression
sizeof ( type-id )
typeid ( expression )
typeid ( type-id )
::opt delete cast-expression
::opt delete [ ] cast-expression
throw assignment-expressionopt

sizeof выражение срабатывает спокойно от параметра шаблона.

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



119 / 9 / 2

Регистрация: 06.09.2017

Сообщений: 82

04.11.2017, 01:01

2

Цитата
Сообщение от Pechkin80
Посмотреть сообщение

sizeof выражение срабатывает спокойно от параметра шаблона.

Тип sizeof(…) всегда size_t, он не зависит от типа того, что в скобках. Поэтому и не type-dependent.



1



21 / 19 / 7

Регистрация: 14.03.2014

Сообщений: 249

05.11.2017, 23:03

 [ТС]

3

animefan, Это итак понятно. Но там многозначность трактовки. Толи они рассматривают данный случай как исключение и тогда то что вы говорите, либо как уточнение предыдущего правила и тогда sizeof(…) при зависимом типе впринцепе должен быть illformed.

Щас вот читаю про точку инстанцирования. Столько разнообразных случаев и ни одного примера.
Может где это более подробно рассмотрено ?
ISO 14882:2003 14.6.4.1

For a function template specialization, a member function template specialization, or a specialization for a
member function or static data member of a class template, if the specialization is implicitly instantiated
because it is referenced from within another template specialization and the context from which it is referenced
depends on a template parameter, the point of instantiation of the specialization is the point of instantiation
of the enclosing specialization. Otherwise, the point of instantiation for such a specialization immediately
follows the namespace scope declaration or definition that refers to the specialization.
2 If a function template or member function of a class template is called in a way which uses the definition of
a default argument of that function template or member function, the point of instantiation of the default
argument is the point of instantiation of the function template or member function specialization.
3 For a class template specialization, a class member template specialization, or a specialization for a class
member of a class template, if the specialization is implicitly instantiated because it is referenced from
within another template specialization, if the context from which the specialization is referenced depends
on a template parameter, and if the specialization is not instantiated previous to the instantiation of the
enclosing template, the point of instantiation is immediately before the point of instantiation of the enclosing
template. Otherwise, the point of instantiation for such a specialization immediately precedes the
namespace scope declaration or definition that refers to the specialization.



0



119 / 9 / 2

Регистрация: 06.09.2017

Сообщений: 82

06.11.2017, 00:06

4

Цитата
Сообщение от Pechkin80
Посмотреть сообщение

Но там многозначность трактовки.

Там однозначность трактовки.

Цитата
Сообщение от Pechkin80
Посмотреть сообщение

как уточнение предыдущего правила

Какое ещё уточнение? Предыдущее правило говорит об id-expression, а также о нескольких других видах выражений, к которым sizeof не относится.

Цитата
Сообщение от Pechkin80
Посмотреть сообщение

sizeof(…) при зависимом типе впринцепе должен быть illformed.

«Expressions of the following forms are never type-dependent» это констатация факта, а не правило, чтобы его можно было нарушить.



0



21 / 19 / 7

Регистрация: 14.03.2014

Сообщений: 249

06.11.2017, 00:12

 [ТС]

5

animefan, «Expressions of the following forms are never type-dependent» Означает только чем оно не является, как исключение из ранее определённого правила:
An id-expression is type-dependent if it contains:
— an identifier that was declared with a dependent type,
— a template-id that is dependent,
— a conversion-function-id that specifies a dependent type,
— a nested-name-specifier that contains a class-name that names a dependent type.
И тут оба варианта логичны:
1)ill-formed
2)скомпилируется как независимое выражение.



0



119 / 9 / 2

Регистрация: 06.09.2017

Сообщений: 82

06.11.2017, 00:25

6

Цитата
Сообщение от Pechkin80
Посмотреть сообщение

как исключение из ранее определённого правила:
An id-expression is type-dependent if

Давно sizeof(…) стало id-expression?



0



21 / 19 / 7

Регистрация: 14.03.2014

Сообщений: 249

06.11.2017, 00:34

 [ТС]

7

animefan,
14.6.2.2 Type-dependent expressions
«Except as described below, an expression is type-dependent if any subexpression is type-dependent.»
An id-expression is type-dependent if it contains:
— an identifier that was declared with a dependent type,
— a template-id that is dependent,
— a conversion-function-id that specifies a dependent type,
— a nested-name-specifier that contains a class-name that names a dependent type.
Так лучше ?



0



119 / 9 / 2

Регистрация: 06.09.2017

Сообщений: 82

06.11.2017, 00:38

8

Pechkin80, и что тебе непонятно в «Except as described below»? Не знаешь, как «except» переводится?



0



21 / 19 / 7

Регистрация: 14.03.2014

Сообщений: 249

06.11.2017, 00:40

 [ТС]

9

animefan, Мне всё понятно. Я лишь утверждаю то о чём писал выше. И если честно мне уже неактуально. С точкой инстанцирования гораздо всё запутанней.



0



119 / 9 / 2

Регистрация: 06.09.2017

Сообщений: 82

06.11.2017, 00:41

10

Цитата
Сообщение от Pechkin80
Посмотреть сообщение

Мне всё понятно.

Тогда к чему было

Цитата
Сообщение от Pechkin80
Посмотреть сообщение

там многозначность трактовки. Толи они рассматривают данный случай как исключение, либо как уточнение

?



0



21 / 19 / 7

Регистрация: 14.03.2014

Сообщений: 249

06.11.2017, 01:15

 [ТС]

11

animefan, Спасибо, разобрался. Осталось разобрать каждый случай с точкой инстанцирования.

Щас вот читаю про точку инстанцирования. Столько разнообразных случаев и ни одного примера.
Может где это более подробно рассмотрено ?
ISO 14882:2003 14.6.4.1

For a function template specialization, a member function template specialization, or a specialization for a
member function or static data member of a class template, if the specialization is implicitly instantiated
because it is referenced from within another template specialization and the context from which it is referenced
depends on a template parameter, the point of instantiation of the specialization is the point of instantiation
of the enclosing specialization. Otherwise, the point of instantiation for such a specialization immediately
follows the namespace scope declaration or definition that refers to the specialization.
2 If a function template or member function of a class template is called in a way which uses the definition of
a default argument of that function template or member function, the point of instantiation of the default
argument is the point of instantiation of the function template or member function specialization.
3 For a class template specialization, a class member template specialization, or a specialization for a class
member of a class template, if the specialization is implicitly instantiated because it is referenced from
within another template specialization, if the context from which the specialization is referenced depends
on a template parameter, and if the specialization is not instantiated previous to the instantiation of the
enclosing template, the point of instantiation is immediately before the point of instantiation of the enclosing
template. Otherwise, the point of instantiation for such a specialization immediately precedes the
namespace scope declaration or definition that refers to the specialization.

Добавлено через 28 минут

For a function template specialization, a member function template specialization, or a specialization for a
member function or static data member of a class template, if the specialization is implicitly instantiated
because it is referenced from within another template specialization and the context from which it is referenced
depends on a template parameter, the point of instantiation of the specialization is the point of instantiation
of the enclosing specialization. Otherwise, the point of instantiation for such a specialization immediately
follows the namespace scope declaration or definition that refers to the specialization.

Про первую часть всё понятно, хотя лихо завинчено.
template <typename T> class Tobject {};
template <template<T> class U> class Tsubject {};
// Если я правильно понял вот о чём речь:
template <> Tsubject<Toject<T > > {};
Непонятно про Otherwise. О каких случаях идёт речь ?

2 If a function template or member function of a class template is called in a way which uses the definition of
a default argument of that function template or member function, the point of instantiation of the default
argument is the point of instantiation of the function template or member function specialization.

Здесь вроде всё понятно.

3 For a class template specialization, a class member template specialization, or a specialization for a class
member of a class template, if the specialization is implicitly instantiated because it is referenced from
within another template specialization, if the context from which the specialization is referenced depends
on a template parameter, and if the specialization is not instantiated previous to the instantiation of the
enclosing template, the point of instantiation is immediately before the point of instantiation of the enclosing
template. Otherwise, the point of instantiation for such a specialization immediately precedes the
namespace scope declaration or definition that refers to the specialization.

Это как я понял случай 1, с той лишь разницов что шаблон-субъект, использующий специализированный шаблон-объект не инстанцирован.



0



Pechkin80

21 / 19 / 7

Регистрация: 14.03.2014

Сообщений: 249

12.11.2017, 14:56

 [ТС]

12

Может кто нибудь пояснит, частичная специализация шаблонов функций запрещена потому что нигде не описана ?

Добавлено через 21 час 52 минуты
Вот ещё один прикол. Дружественный шаблонный метод, который в качестве параметра принимает шаблон.

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#ifndef FRIENDS_H
#define FRIENDS_H
#include "iostream"
 
template <typename T1> class Tgranter2;
 
class TFriendClass
{
public:
    template <typename T1>
    void friend_member(T1& t1)
    {
        t1.privatevar = 5;
    }
    // Ошибка компиляции 
    /*
     friends.h:53: ошибка: prototype for 'template<class T1, template<class> class typedef U U> void TFriendClass::friend_member3(Tgranter2<int>&)' does not match any in class 'TFriendClass'
     friend void TFriendClass::friend_member3(Tgranter2<_T1>& t1);
                 ^
     */
    template  <typename T1, template< typename > class U>
    void friend_member3(U<T1>& t1);
    template <typename T1>
    void friend_member4(Tgranter2<T1>& t1)
    {
        t1.privatevar2 = 5;
    }
};
 
 
template <typename _T1>
class Tgranter2
{
    int privatevar2;    
    template  <typename T1, template <class> class U>
    friend void TFriendClass::friend_member3(Tgranter2<_T1>& t1);
    template <typename T2>
    friend void TFriendClass::friend_member4(Tgranter2<T2>& t1);
};



0



495 / 209 / 70

Регистрация: 27.05.2016

Сообщений: 557

12.11.2017, 15:41

13

У TFriendClass::friend_member3 нет определения.



0



Pechkin80

21 / 19 / 7

Регистрация: 14.03.2014

Сообщений: 249

12.11.2017, 15:49

 [ТС]

14

notAll, Я может не понял ваш ответ, но вот пример с опрелением:

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#ifndef FRIENDS_H
#define FRIENDS_H
#include "iostream"
 
class Tgranter;
template <typename T1> class Tgranter2;
 
class TFriendClass
{
public:
    template <typename T1>
    void friend_member(T1& t1)
    {
        t1.privatevar = 5;
    }
    // Ошибка компиляции
    /*
     friends.h:53: ошибка: prototype for 'template<class T1, template<class> class typedef U U> void TFriendClass::friend_member3(Tgranter2<int>&)' does not match any in class 'TFriendClass'
     friend void TFriendClass::friend_member3(Tgranter2<_T1>& t1);
                 ^
     */
    template  <typename T1, template< typename > class U>
    void friend_member3(U<T1>& t1)
    {
        // Do Nothing определение
    }
    template <typename T1>
    void friend_member4(Tgranter2<T1>& t1)
    {
        t1.privatevar2 = 5;
    }
};
 
 
 
template <typename T1>
void friend_func2(T1& t1)
{
    t1.privatevar = 55;
    std::cout << " func primary friend";
}
 
template <>
void friend_func2<Tgranter>(Tgranter& t1)
{
    //t1.privatevar = 55;
    std::cout << " func specialization friend";
}
 
class Tgranter
{
    int privatevar;    
    template <typename T1> friend void friend_func2(T1& t1);    
    template <typename T1> friend void TFriendClass::friend_member(T1 & t1);
};
 
template <typename _T1>
class Tgranter2
{
    int privatevar2;    
    template  <typename T1, template <class> class U>
    friend void TFriendClass::friend_member3(U<_T1>& t1);
    template <typename T2>
    friend void TFriendClass::friend_member4(Tgranter2<T2>& t1);
};
 
 
template <>
void TFriendClass::friend_member(Tgranter& t1)
{
    t1.privatevar = 5;
}
 
#endif // FRIENDS_H

Только это ничего не изменило.



0



notAll

495 / 209 / 70

Регистрация: 27.05.2016

Сообщений: 557

12.11.2017, 15:54

15

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
 
template <typename T1> class Tgranter2;
 
class TFriendClass
{
public:
    template <typename T1>
    void friend_member(T1& t1)
    {
        t1.privatevar = 5;
    }
 
    template  <typename T1, template< typename > class U>
    void friend_member3(U<T1>& u) {std::cout << u.privatevar2 << "n";};
 
    template <typename T1>
    void friend_member4(Tgranter2<T1>& t1)
    {
        t1.privatevar2 = 5;
    }
};
 
 
template <typename _T1>
class Tgranter2
{
    int privatevar2 = 42;
 
    template  <typename T = _T1, template <typename> class U>
    friend void TFriendClass::friend_member3(U<T>&);
 
    template <typename T = _T1>
    friend void TFriendClass::friend_member4(Tgranter2<T>&);
};
 
int main()
{
    Tgranter2<int> tg2;
    TFriendClass Tfriend;
    Tfriend.friend_member3(tg2);
    Tfriend.friend_member4(tg2);
    Tfriend.friend_member3(tg2);
}



0



21 / 19 / 7

Регистрация: 14.03.2014

Сообщений: 249

12.11.2017, 16:19

 [ТС]

16

notAll, Копи-паст того что вы написали выдал:

C:MySoftwarestudy_cpptest14friendsmain.cpp:31 :51: error: default argument for template parameter for class enclosing ‘void TFriendClass::friend_member3(U<T>&)’
friend void TFriendClass::friend_member3(U<T>&);
^
C:MySoftwarestudy_cpptest14friendsmain.cpp:34 :59: error: default argument for template parameter for class enclosing ‘void TFriendClass::friend_member4(Tgranter2<T>&)’
friend void TFriendClass::friend_member4(Tgranter2<T>&);
^
C:MySoftwarestudy_cpptest14friendsmain.cpp: In instantiation of ‘class Tgranter2<int>’:
C:MySoftwarestudy_cpptest14friendsmain.cpp:39 :20: required from here
C:MySoftwarestudy_cpptest14friendsmain.cpp:31 :17: error: prototype for ‘template<class T, template<class> class typedef U U> void TFriendClass::friend_member3(U<T>&)’ does not match any in class ‘TFriendClass’
friend void TFriendClass::friend_member3(U<T>&);
^
C:MySoftwarestudy_cpptest14friendsmain.cpp:15 :10: error: candidate is: template<class T1, template<class> class U> void TFriendClass::friend_member3(U<T1>&)
void friend_member3(U<T1>& u) {std::cout << u.privatevar2 << «n»;};
^
C:MySoftwarestudy_cpptest14friendsmain.cpp: In instantiation of ‘void TFriendClass::friend_member3(U<T1>&) [with T1 = int; U = Tgranter2]’:
C:MySoftwarestudy_cpptest14friendsmain.cpp:41 :31: required from here
C:MySoftwarestudy_cpptest14friendsmain.cpp:28 :23: error: ‘int Tgranter2<int>:rivatevar2′ is private
int privatevar2 = 42;
^
C:MySoftwarestudy_cpptest14friendsmain.cpp:15 :46: error: within this context
void friend_member3(U<T1>& u) {std::cout << u.privatevar2 << «n»;};

Добавлено через 7 минут
Короче гора ошибок стала больше.

Добавлено через 3 минуты
Вы каким компилятором это компилировали ?



1



495 / 209 / 70

Регистрация: 27.05.2016

Сообщений: 557

12.11.2017, 16:25

17



1



21 / 19 / 7

Регистрация: 14.03.2014

Сообщений: 249

12.11.2017, 16:31

 [ТС]

18

notAll, Я дико извиняюсь, но под форточки самое лучшее это mingw-w64 4.8.3. Лучшего просто нет ещё. Не сделали. Для полноценной поддержки с++11 хватает.

Добавлено через 1 минуту
Переходить на шланг ?



0



119 / 9 / 2

Регистрация: 06.09.2017

Сообщений: 82

12.11.2017, 16:40

19

Pechkin80, в 4.8.3 нет полноценной поддержки C++11.



0



21 / 19 / 7

Регистрация: 14.03.2014

Сообщений: 249

12.11.2017, 16:46

 [ТС]

20

animefan, Судя по данному примеру, у них и с полноценной поддержкой С++03 не всё благополучно. Я читал в интернете что есть, но возможно вы знаете больше. Будут интересны ваши доводы.



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

12.11.2017, 16:46

Помогаю со студенческими работами здесь

Пояснение
Доброго времени суток!
Для чего это? Это как то будет отображаться в режиме 1С Предприятие?

Пояснение
Препод-редиска,говорит объясни мне каждую строчку,а я как четвероногий друг:понимаю но объяснить не…

пояснение к коду
помогите пожалуйста. напишите поянение к коду.

var f1, f2 : text;
s : string;
i :…

Пояснение кода
Кто знает,поясните пожалуйста код :)

using System;
using System.Collections;
using…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

20

Может кто-нибудь просветить меня, что не так с этим кодом:

template<typename B=int> // <<<< =int is provoking the error
struct Foo
{
std::array<B,10> data;

template<typename F>
void iterate(F f) const
{
for(unsigned i=0; i<10; i++) {
f(i, data[i]);
}
}

friend std::ostream& operator<<(std::ostream& os, const Foo<B>& a) // Line 17
{
a.iterate([&os](unsigned i, const B& x) {
os << i << "=" << x << "n";
});
return os;
}
};

Сообщение об ошибке с GCC 4.8.1 и --std=c++11:

test.cpp: In function ‘std::ostream& operator<<(std::ostream&, const Foo<B>&)’:
test.cpp:17:41: error: default argument for template parameter for class enclosing ‘operator<<(std::ostream&, const Foo<B>&)::__lambda0’
a.iterate([&os](unsigned i, const B& x) {

4

Решение

a.iterate([&os](unsigned i, const B& x) {
os << i << "=" << x << "n";
});

Введенная здесь лямбда-функция имеет эффект объявления «неназванного» локального класса в области видимости функции в пределах operator<< функция тела. Мы можем написать наш собственный объект функтор, чтобы получить аналогичный эффект:

struct lambda {
std::ostream& os;

lambda(std::ostream& os_) : os(os_) {}

void operator()(unsigned i, const B& x) {
os << i << "=" << x << "n";
}
};
a.iterate(lambda(os));

Это вызывает аналогичную ошибку в g ++:

error: default argument for template parameter for class enclosing
‘operator<<(std::ostream&, const Foo<B>&)::lambda::lambda’

Вот SSCCE:

template <typename T = int>
struct Foo
{
friend void f() {
struct local {};
}
};

И ошибка, которую он вызывает:

error: default argument for template parameter for class enclosing
‘f()::local::local’

Это уже сообщалось как Ошибка GCC 57775.

Как отмечает @PiotrNycz, вы можете обойти, перемещая тело функции operator<< вне шаблона класса.

1

Другие решения

Bug 53856
Default argument allowed on member defined outside of class template

Summary:

Default argument allowed on member defined outside of class template

Status: RESOLVED
FIXED

Alias:

None

Product:

gcc

Classification:

Unclassified

Component:

c++

(show other bugs)

Version:

4.8.0

Importance:

P3
normal

Target Milestone:

6.0

Assignee:

Not yet assigned to anyone

URL:


Keywords:

accepts-invalid, rejects-valid

Depends on:


Blocks:


Reported: 2012-07-04 16:39 UTC by Jonathan Wakely
Modified: 2021-08-04 19:32 UTC
(History)

CC List:

2
users

(show)

See Also:

  • 61975

Host:

Target:

Build:

Known to work:

Known to fail:

3.4.3, 4.1.2, 4.6.3, 4.8.0

Last reconfirmed:

2015-09-22 00:00:00


Attachments
Add an attachment
(proposed patch, testcase, etc.)

Note
You need to
log in
before you can comment on or make changes to this bug.


PlatformIO Community

Loading

Bug 1149294
template argument deduction/substitution fails when default argument is lambda

Summary:

template argument deduction/substitution fails when default argument is lambda

Keywords:
Status: CLOSED
ERRATA

Alias:

None

Product:

Red Hat Developer Toolset

Classification:

Red Hat

Component:

gcc


Sub Component:



Version:

DTS 3.0 RHEL 7

Hardware:

All

OS:

Linux

Priority:

medium
Severity:

medium

Target Milestone:

alpha

Target Release:

3.0

Assignee:

Jakub Jelinek

QA Contact:

Miroslav Franc

Docs Contact:


URL:


Whiteboard:

Depends On:


Blocks:


TreeView+

depends on /

blocked

Reported: 2014-10-03 16:41 UTC by Miroslav Franc
Modified: 2016-02-01 02:29 UTC
(History)

CC List:

7
users

(show)

Fixed In Version:

devtoolset-3-gcc-4.9.2-5.el6

Doc Type:

Bug Fix

Doc Text:

No description necessary

Clone Of:

Environment:

Last Closed:

2015-04-23 07:53:48 UTC

Target Upstream Version:


Attachments (Terms of Use)
Add an attachment
(proposed patch, testcase, etc.)
Links

System ID Private Priority Status Summary Last Updated
Red Hat Product Errata RHBA-2015:0880 0
normal
SHIPPED_LIVE
devtoolset-3-gcc bug fix and enhancement update
2015-04-23 11:53:28 UTC



Я пытаюсь избежать концепций в главной ветки моих проектов, поэтому мне нужна альтернатива с type_trait:

Мне нужен класс, который несколько функций изменится в зависимости от значения bool.

Кто-то уже предложил мне разделить мой класс, но этот случай здесь не имеет смысла. В каком-то контексте это пул, в котором функция удаления и некоторые другие будут изменены, если тип объекта пула может быть общим или нет.

Поэтому я попытался использовать std::enable_if, но все еще есть некоторые ошибки (Я хочу, чтобы объявление и реализация были отдельными).

#include  <type_traits>

template < typename Object, bool Shared = false >
class Foo {

  template < bool S = Shared, typename std::enable_if<S>::type* = nullptr >
  void   bar();

  template < bool S = Shared, typename std::enable_if<!S>::type* = nullptr >
  void   bar();
};

template < typename Object,
           bool Shared >
template < bool S, typename std::enable_if<S>::type* = nullptr >
void   Foo<Object, Shared>::bar() {
    //do something
}


template < typename Object,
           bool Shared >
template < bool S, typename std::enable_if<!S>::type* = nullptr >
void   Foo<Object, Shared>::bar() {
  //do nothing
}

int main() {

  Foo<int> test;
  return 0;
}

Test3.cpp:16:33: error: default argument for template parameter for class enclosing ‘void Foo<Object, Shared>::bar()’
 void   Foo<Object, Shared>::bar() {
                                 ^
Test3.cpp:24:33: error: default argument for template parameter for class enclosing ‘void Foo<Object, Shared>::bar()’
 void   Foo<Object, Shared>::bar() {

EDIT: удалена ошибка копирования/вставки

Понравилась статья? Поделить с друзьями:
  • Error decompressing unknown compression method weak auras
  • Error decompressing mp3 file
  • Error decompressing data corrupted installer перевод
  • Error decompressing data corrupted installer как исправить fl studio
  • Error declared as function returning an array