Вариации на тему деклараций
От: rg45 СССР  
Дата: 07.12.09 21:45
Оценка: 159 (16)
Привет всем!

Прошу прощения, если баян, но я, мягко говоря, удивлен.

Как вы считаете, имеет ли какой-нибудь смысл, например, такое объявление:
typedef int Foo(const char*) const;

и в какой области такое объявление может располагаться? Оказывается, имеет и может располагаться вне определения класса, не смотря на модификатор const.

А вот вполне себе well-formed программка, можете откомпилировать и запустить. Обратите внимание на объявления и определения свободных функций и функций-членов:
#include <string>
#include <iostream>

typedef std::string Foo(const char*);
typedef std::string Goo(const char*) const;

//Свободные функции
Foo f1;
Foo f2;
Foo f3;

std::string f1(const char* str) { return "f1 -- " + std::string(str); }
std::string f2(const char* str) { return "f2 -- " + std::string(str); }
std::string f3(const char* str) { return "f3 -- " + std::string(str); }

//Функции-члены
struct A
{
  Foo f1;
  Foo f2;
  Foo f3;
  
  Goo g1;
  Goo g2;
  Goo g3;
};

std::string A::f1(const char* str) { return "A::f1 -- " + std::string(str); }
std::string A::f2(const char* str) { return "A::f2 -- " + std::string(str); }
std::string A::f3(const char* str) { return "A::f3 -- " + std::string(str); }

std::string A::g1(const char* str) const { return "A::g1 -- " + std::string(str); }
std::string A::g2(const char* str) const { return "A::g2 -- " + std::string(str); }
std::string A::g3(const char* str) const { return "A::g3 -- " + std::string(str); }

//Использование
int main()
{
  A a;

  std::cout << f1("abc") << std::endl;
  std::cout << f2("def") << std::endl;
  std::cout << f3("ghi") << std::endl;

  std::cout << a.f1("jkl") << std::endl;
  std::cout << a.f2("mno") << std::endl;
  std::cout << a.f3("pqr") << std::endl;

  std::cout << a.g1("stu") << std::endl;
  std::cout << a.g2("vwx") << std::endl;
  std::cout << a.g3("yza") << std::endl;
}


А вот пункт стандарта, который все это благословляет: 9.3/9. Для тех, у кого нет под рукой стандарта цитирую:

[Note: a member function can be declared (but not defined) using a typedef for a function type. The resulting member function has exactly the same type as it would have if the function declarator were provided explicitly, see 8.3.5. For example,

typedef void fv(void);
typedef void fvc(void) const;
struct S {
fv memfunc1; // equivalent to: void memfunc1(void);
void memfunc2();
fvc memfunc3; // equivalent to: void memfunc3(void) const;
};
fv S::* pmfv1 = &S::memfunc1;
fv S::* pmfv2 = &S::memfunc2;
fvc S::* pmfv3 = &S::memfunc3;

Also see 14.3. ]

--
Не можешь достичь желаемого — пожелай достигнутого.
 
Подождите ...
Wait...
Пока на собственное сообщение не было ответов, его можно удалить.